﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Phone.BackgroundTransfer;
using System.IO.IsolatedStorage;
using System.Collections.ObjectModel;
using Windows.Storage.FileProperties;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;

namespace FondoDinamico.ViewModel
{
    public class FondoDinamicoViewModel:NotificationObject
    {

        private MVVMComun.FondoDinamicoModel fondoModel;
        
        private string etiqueta;

        public string Etiqueta
        {
            get { return etiqueta; }
            set { etiqueta = value;
            OnPropertyChanged(this);
            }
        }

        private ObservableCollection<MVVMComun.Foto> fotosDescargadas;

        public ObservableCollection<MVVMComun.Foto> FotosDescargadas
        {
            get { return fotosDescargadas; }
            set { fotosDescargadas = value;
            OnPropertyChanged(this);
            }
        }


        public FondoDinamicoViewModel(){

            LoadSettings();
            getFotosDescargadasyProcesarNuevas();
            regiserPeriodicTask();
  
        }

        private void regiserPeriodicTask()
        {
            var taskName = "CambiarFondoTask";
            ResourceIntensiveTask  pt = new ResourceIntensiveTask(taskName);
            pt.Description = "Actualizar el Fondo de Pantalla.";
            
            var oldtask = ScheduledActionService.Find(taskName);
            if (oldtask != null)
                ScheduledActionService.Remove(taskName);
            ScheduledActionService.Add(pt);
            ScheduledActionService.LaunchForTest(taskName,new TimeSpan(0,0,10));
        }

        private void limpiarBTS()
        {
            foreach (var item in BackgroundTransferService.Requests)
            {
                ProcessTransfer(item);
            }

        }

        private void configModel()
        {
            fondoModel = new MVVMComun.FondoDinamicoModel();
            fondoModel.FotosCargadas += (s, e) =>
            {
                procesarFotos(e.Result);
            };
        }

        private void procesarFotos(List<MVVMComun.Foto> fotos)
        {
            const string path= "/shared/transfers/";
            List<MVVMComun.Foto> fotosNuevas = new List<MVVMComun.Foto>();
            getFotosNuevas(fotos, path, FotosDescargadas.ToList(), fotosNuevas);
            descargaFotos(fotosNuevas);
       
        }

        private  void descargaFotos(List<MVVMComun.Foto> fotosNuevas)
        {
            foreach (var item in fotosNuevas)
            {

                if (BackgroundTransferService.Requests.Count() < 25)
                {
                    try
                    {
                        Uri requestUri = new Uri(item.Url);
                        Uri downloadUri = new Uri("/shared/transfers/" + getFileName(item.Url), UriKind.RelativeOrAbsolute);
                        BackgroundTransferRequest btr = new BackgroundTransferRequest(requestUri, downloadUri);
                         btr.Tag = getFileName(item.Url);
                        BackgroundTransferService.Add(btr);

                        //btr.TransferStatusChanged += (s, e) => {


                        //   // updateTile();


                        //    if (e.Request.TransferStatus.Equals(TransferStatus.Completed))
                        //    {
                        //      // updateTile();

                        //        ShellToast st = new ShellToast();
                        //        st.Title = "Fondo Dinamico";
                        //        st.Content = "Nueva Imagen" + " Descargada";
                        //        st.Show();
                        //    }
                        
                        //};
                  
                    }
                    catch (Exception e)
                    {
                        

                    }
                }
            
            }
        }

        private void updateTile()
        {
            var tile = Microsoft.Phone.Shell.ShellTile.ActiveTiles.First();

            var cdata = new Microsoft.Phone.Shell.CycleTileData();
         //   getFotosDescargadas();
            List<Uri> lastImages = new List<Uri>();


            int counter =1;
            for (int i = 0; i < FotosDescargadas.Count; i++)
            {
                if (counter == 9)
                    break;
                var url = FotosDescargadas[i].Url.Replace(@"\", @"/");
                url = getFileName(url);
               
                var schema = "isostore:/";
                var uri = new Uri(schema + "shared/Shellcontent/" + url, UriKind.RelativeOrAbsolute);

                lastImages.Add(uri);
                counter++;
            }



            cdata.CycleImages = lastImages;
            tile.Update(cdata);
        }

        private  string getFileName(string transferFileName)
        {
            transferFileName=transferFileName.Replace(@"\", @"/");

            string downloadFile = transferFileName.Substring(transferFileName.LastIndexOf("/") + 1);
            return downloadFile;
        }

        private  void getFotosNuevas(List<MVVMComun.Foto> fotos, string path, List<MVVMComun.Foto> fotosYaDescargadas, List<MVVMComun.Foto> fotosNuevas)
        {
            foreach (var item in fotos)
            {
                bool agregar= true;

                foreach (var itemdescargados in fotosYaDescargadas)
                {

                    if(getFileName(item.Url).Equals(getFileName(itemdescargados.Url) ))
                        agregar = false;
                }
                
                if(agregar)
                    fotosNuevas.Add(item);
            }
        }

        private async void getFotosDescargadasyProcesarNuevas()
        {
            await getFotosDescargadas();
            limpiarBTS();
            configModel();
            fondoModel.getFotos(Etiqueta);
           // updateTile();

            
        }

        private async Task getFotosDescargadas()
        {
            var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var folderToSave = await localfolder.CreateFolderAsync("shared", Windows.Storage.CreationCollisionOption.OpenIfExists);
            var folderToSave2 = await folderToSave.CreateFolderAsync("transfers", Windows.Storage.CreationCollisionOption.OpenIfExists);

            var files = await folderToSave2.GetFilesAsync();

            FotosDescargadas = new ObservableCollection<MVVMComun.Foto>(new List<MVVMComun.Foto>());

            var folertocopy = (await (await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFolderAsync("shared", Windows.Storage.CreationCollisionOption.OpenIfExists)).CreateFolderAsync("ShellContent", Windows.Storage.CreationCollisionOption.OpenIfExists));          

            foreach (var item in files)
            {

                var pa = item.Path;

                var prop = await item.GetBasicPropertiesAsync();

                if (prop.Size > 0)
                {
                    FotosDescargadas.Add(new MVVMComun.Foto() { Url = item.Path, Fecha = prop.DateModified.Date });


                    try
                    {
                        await item.CopyAsync(folertocopy);
                    }
                    catch (Exception)
                    {
                        
                    }
                
                
                }
            }

            FotosDescargadas = new ObservableCollection<MVVMComun.Foto>(FotosDescargadas.OrderByDescending(f => f.Fecha));
      
        }

        
        private  void LoadSettings()
        {
            System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("Etiqueta"))
            {
                Etiqueta = settings["Etiqueta"].ToString();
            }
            else {
                Etiqueta = "Venezuela Barquisimeto";
                settings.Add("Etiqueta", Etiqueta);
            }

         
        }

        public void UpdateSettings()
        {
            System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("Etiqueta"))
            {
                if (!settings["Etiqueta"].ToString().Equals(Etiqueta))
                {
                    settings["Etiqueta"] = Etiqueta; 
                    getFotosDescargadasyProcesarNuevas();
                }
            }
            else
            {
                settings.Add("Etiqueta", Etiqueta);
                getFotosDescargadasyProcesarNuevas();
   
            }
        }
        
        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
                case TransferStatus.Completed:
                    if (transfer.TransferStatus == TransferStatus.Completed)
                    {
                        BackgroundTransferService.Remove(transfer);
                    }
             
                    break;
            }
        }
    
    
    }
}
